package CtrLag;
import ModelLag.*;
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * The LoanCtrl class is used to control the Loan and LoanContainer classes by calling their methods
 * 
 * @author (Lackshan, Mikkel, Nick, patrick, Simon, Yousef) 
 * @project (Tema design)
 * @version (2014.11.05)
 */
public class LoanCtr
{
    private LoanContainer lCon;
    private PersonCtr pCtr;
    private DVDCtr dCtr;
    
    /**
     * Constructor for objects of class LoanCtrl
     */
    public LoanCtr()
    {
        lCon = LoanContainer.getInstance();
        pCtr = new PersonCtr();
        dCtr = new DVDCtr();
    }
    
    /**
     * Find a person based on the Persons phonenumber
     * 
     * @param phone the phone of the person
     * @return a Person
     */
    public Person findPerson(String phone){
        return pCtr.findPerson(phone);
    }
    
    /**
     * Find a Copy based on the copy´s serialnumber
     * 
     * @param serialNumnber the serialnumber of the Copy
     * @return a Copy with the specific serialnumber
     */
    public Copy findCopy(String serialNumber){
        return dCtr.findCopy(serialNumber);
    }
    
    /**
     * Create a new loan to the system
     * 
     * @param person the person the loan is associated to
     * @param loanDate the beginning loan of the loan
     * @param returnDate the loan return date
     * @param copy the DVD copy which is to be lent out
     */
    public void CreateLoan(Person person, String returnDate, Copy copy){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date ld = new Date();
            Date rd = sdf.parse(returnDate);
            Loan newLoan = new Loan(person, ld, rd, copy);
            lCon.addLoan(newLoan);
        }catch(Exception e){
        }
    }
    
    /**
     * Find´s a loan based on the loans DVD copy´s serialnumber
     * 
     * @param serialNumber the copy´s serialnumber 
     * @return a Loan object
     */
    public Loan findLoan(String serialNumber) {     
        return lCon.findLoan(serialNumber);
    }
    
    /**
     * End a loan in the system
     * 
     * @param l the Loan to be ended
     * @param returnDate the date of which the loan was returned
     * 
     * @return true if the loan was returned on time and false if not
     */
    public boolean endLoan(Loan l){
        l.endLoan();
        lCon.deleteLoan(l);
       
        return l.returnedOntime();
    }
}
